﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using iwintip.Util;

namespace iwintip.RssReader
{
    public class NewsReader
    {
        private XmlTextReader _reader;
        private XmlDocument _xmlDocument;
        private List<FeedItem> feedItems = new List<FeedItem>();

        public NewsReader()
        {
            _xmlDocument = new XmlDocument();
        }

        public List<FeedItem> GetRssByTag(String url, int nResultsInView)
        {
            // Load the feed in
            _reader = new XmlTextReader(url);

            // Add the feed to the document
            _xmlDocument.Load(_reader);

            // Get the <feed> element.
            XmlNodeList feeds = _xmlDocument.GetElementsByTagName("item");
            if (feeds.Count <= nResultsInView)
            {
                nResultsInView = feeds.Count;
            }

            int index = 0;       
            foreach (XmlNode feed in feeds)
            {
                FeedItem feedItem = new FeedItem();
                var titleNode = feed.SelectSingleNode("title");
                if (titleNode != null) feedItem.Title = titleNode.InnerText;
                var descriptionNode = feed.SelectSingleNode("description");
                if (descriptionNode != null)
                {
                    feedItem.Description = StringUtil.CatChuoi(descriptionNode.InnerText, 120);
                }
                var linkNode = feed.SelectSingleNode("link");
                if (linkNode != null) feedItem.Link = linkNode.InnerText;
                var pubDateNode = feed.SelectSingleNode("pubDate");
                if (pubDateNode != null)
                    feedItem.Date = pubDateNode.InnerText;
                if (feed.SelectSingleNode("enclosure") != null)
                {
                    feedItem.Image = feed.SelectSingleNode("enclosure").Attributes["url"].Value;
                }
                else
                {
                    feedItem.Image = "http://www.hep.edu.vn/Contents/photo_not_available.jpg";
                }
                var sourceNode = feed.SelectSingleNode("source");
                if (sourceNode != null)
                    feedItem.Source = sourceNode.InnerText;

                feedItem.Index = index;
                feedItems.Add(feedItem);
                index++;

                if (feedItems.Count == nResultsInView)
                    break;
            }


            return feedItems;
        }
    }
}